package com.shengde.jinwawaforleader.model.myJob.classStatus;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.utils.UmengShareUtil;
import com.shengde.jinwawaforleader.views.photoview.PhotoView;
import com.umeng.socialize.UMShareAPI;
import com.videogo.universalimageloader.core.DisplayImageOptions;
import com.videogo.universalimageloader.core.ImageLoader;
import com.videogo.universalimageloader.core.assist.ImageScaleType;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 查看相册大图
 */
public class AlbumImageBrowserActivity extends BaseActivity implements OnPageChangeListener {

	private static final String TAG = "AlbumImageBroActivity";
	private ViewPager viewpager;
	private int pos = 0;
	private TextView share;
	private TextView tv_back;
	private TextView tv_title;
	String imagpath;
	private List<String>list;
	private String PATH = Environment.getExternalStorageDirectory() + "/金娃娃/";
	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.image_browser);
		if (Build.VERSION.SDK_INT >= 11) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectAll()
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().build());
		}

	}

	@Override
	public void initView() {
		tv_back = (TextView) findViewById(R.id.tv_back);
		share = (TextView) findViewById(R.id.fill_add);
		tv_title = (TextView) findViewById(R.id.tv_title);

	}

	@Override
	public void initData() {
		share.setText(getString(R.string.share));
		tv_title.setText(getString(R.string.picture));
		list = getIntent().getStringArrayListExtra("list");
		Log.i(TAG, "initData:size" + list.size());
		pos = getIntent().getIntExtra("pos", 0);
		imagpath = list.get(pos);
		viewpager = (ViewPager) findViewById(R.id.viewpager);

		viewpager.setAdapter(new SamplePagerAdapter(list));
		viewpager.setCurrentItem(pos);
	}

	@Override
	public void initListener() {
		share.setOnClickListener(this);
		tv_back.setOnClickListener(this);
		viewpager.setOnPageChangeListener(this);
	}
	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()){
			case R.id.fill_add:
				String url = BaseProtocol.IMG_BASE + imagpath;
				UmengShareUtil.share(AlbumImageBrowserActivity.this,"班级照片",url,url,url);
				break;
			case R.id.tv_back:
				finish();
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int position) {
		imagpath = list.get(position); // 选中状态的图片路径

	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}
	class SamplePagerAdapter extends PagerAdapter {
		List<String> list;

		public SamplePagerAdapter(List<String> list) {
			// TODO Auto-generated constructor stub
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		private final DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.logo)
				.showImageOnFail(R.drawable.logo).cacheInMemory(true)
				.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565)
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build();

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			PhotoView photoView = new PhotoView(container.getContext());

			ImageLoader.getInstance().displayImage(
					BaseProtocol.IMG_BASE + list.get(position), photoView,
					options);
			// string = c.path; viewpager会初始上下个要显示费界面，不能在这给图片路径
			photoView.setScaleType(ScaleType.FIT_CENTER);
			photoView.setBackgroundColor(0);

			// photoView.setImageResource(resourceArr[position]);
			container.addView(photoView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);
			photoView.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					showSave();
					return false;
				}
			});
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}

	protected void showSave() {
		// TODO Auto-generated method stub
		final Dialog dialog = new Dialog(this, R.style.dialog);
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.dialog_save, null);
		dialog.setContentView(contentView);
		dialog.setCanceledOnTouchOutside(true);
		TextView tv_save = (TextView) contentView.findViewById(R.id.tv_save);
		tv_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("---------", imagpath);
				savefile(returnBitmap(BaseProtocol.IMG_BASE + imagpath));
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	protected void savefile(Bitmap bitmap) {
		// TODO Auto-generated method stub
		File dirfile = new File(PATH);
		if (!dirfile.exists()) {
			dirfile.mkdir();
		}
		File filename = new File(PATH + imagpath);
		if (filename.exists()) {
			filename.delete();
		}
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(filename));
			bitmap.compress(Bitmap.CompressFormat.PNG, 80, bos);
			bos.flush();
			bos.close();
			Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.save_success),
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Intent mediaScanIntent = new Intent(
					Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri contentUri = Uri.fromFile(filename);
			mediaScanIntent.setData(contentUri);
			this.sendBroadcast(mediaScanIntent);
		} else {
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
					Uri.parse("file://" + PATH)));
		}

	}

	/**
	 * 获取bitmap
	 */
	private Bitmap returnBitmap(String url) {
		// TODO Auto-generated method stub
		Bitmap bitmap = null;
		InputStream is = null;
		HttpURLConnection con = null;
		try {
			// 建立网络连接
			URL imageURl = new URL(url);
			con = (HttpURLConnection) imageURl.openConnection();
			con.connect();
			is = con.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				is.close();
				con.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		if (bitmap == null) {
			bitmap = BitmapFactory.decodeResource(getApplicationContext()
					.getResources(), R.drawable.logo);
		}
		return bitmap;
	}

}
